package com.hxkj.client.service.taglib.directive;

import com.hxkj.client.service.ResourcesServiceClient;
import com.hxkj.domain.po.Resources;
import com.platform.common.domain.result.ResultDataStruct;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import lombok.extern.log4j.Log4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.Writer;
import java.util.List;
import java.util.Map;


/**
 * @ClassName ScriptResourcesDirective  script资源引入标签
 * @Description TODO
 * @Author Mr.zheng
 * @Date 2018/8/10 17:08
 * @Version 1.0
 */
@Component
@Log4j
public class ScriptResourcesDirective extends AbstractDirective {
    @Autowired
    private ResourcesServiceClient resourcesServiceClient;

    @Value("${cms.realPath}")
    private String Path;

    @Value("${cms.Path}")
    private String cmsPath;

    /**
     * 输入参数，站点ID
     */
    public static final String SITE_ID = "siteId";
    /**
     * 输入参数，站点ID
     */
    public static final String SRC = "src";

    /**
     * 输出对象
     */
    public static final String RESOURCES_PATH = "t";

    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars,
                        TemplateDirectiveBody body) throws TemplateException, IOException {
        try {
            //Mr.zheng:获取参数
            Long siteId = super.getLong(SITE_ID, params) == null ? (Long) super.getCustomAttrbute(env, SITE_ID) : super.getLong(SITE_ID, params);
            String src = super.getString(SRC, params) == null ? "" : super.getString(SRC, params);


            if (StringUtils.isEmpty(src)) {
                log.info("请给出资源文件引入条件");
            }

            Resources resources = new Resources();
            String[] st = src.split("/");
            String resourcesName = st[st.length - 1];

            resources.setResourcesName(resourcesName);
            resources.setSiteId(siteId);
            ResultDataStruct<List<Resources>> resultDataStruct = resourcesServiceClient.getResourcesBySiteId(resources);
            //TODO:返回文件路径待确定
            String path = "";
            if (resultDataStruct.getData() == null) {
                path = "Please give the correct resource file import condition.";
            }
            List<Resources> resourcesList = resultDataStruct.getData();
            for (Resources res : resourcesList) {
                String filename = res.getFileName().concat(res.getResourcesName());
                if (filename.contains(src) && res.getIsDirectory() == 1) {
                    path = res.getPath();
                    break;
                }
            }

            if (StringUtils.isEmpty(path)) {
                resources = new Resources();
                resources.setSiteId(siteId);
                resources.setPath(src);
                List<Resources> resultDataStruct1 = resourcesServiceClient.selectContainPathFolder(resources);
                if (resultDataStruct1 != null && resultDataStruct1.size() > 0) {
                    Resources resources1 = resultDataStruct1.get(0);
                    if (resources1 != null)
                        path = resources1.getPath();
                }
            }
            String note = super.getNote(env);
            StringBuffer sb = new StringBuffer();
            if (!StringUtils.isEmpty(note))
//                path = "<script src=\"" + cmsPath + path + "\" help=\"" + src + "\"></script>";
                path = (sb.append("<script src=\"").append(cmsPath).append(path).append("\" help=\"").append(src).append("\"></script>")).toString();
            else
//                path = "<script src=\"" + Path + path + "\" help=\"" + src + "\"></script>";
                path = (sb.append("<script src=\"").append(Path).append(path).append("\" help=\"").append(src).append("\"></script>")).toString();
            env.setVariable(RESOURCES_PATH, DefaultObjectWrapperBuilderFactory.getDefaultObjectWrapper().wrap(path));
            String userToken = super.getUserToken(env);
            Writer out = env.getOut();
            if (body != null) {
                body.render(env.getOut());
            } else {
                throw new RuntimeException("资源文件所在模板至少要加一个空格");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
